/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.sql.SQLException;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DBController.PelaporanDB;
import model.PelaporanBean;
import model.UserBean;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.jsp.PageContext;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.jni.Socket;

/**
 *
 * @author brlnt
 */
public class PelaporanServlet extends HttpServlet {

    private PelaporanBean dataPelaporan;
    private PelaporanDB pelaporandb;
    private HttpSession session;
    private List listdata;

    /**
     * Menampilkan halaman pelaporan, disertai dengan data pelaporan yang
     * disesuaikan dengan role.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void halamanPelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            session = request.getSession();
            UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
            listdata = new PelaporanDB().getPelaporanByUser(sesiUser.getIdUser());
            request.setAttribute("listdata", listdata);
            request.setAttribute("title", "Pelaporan");
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/pelaporan.jsp");
            rd.forward(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        session = request.getSession();
        Object ub = session.getAttribute("sesiUser");
        UserBean ubean = (UserBean) ub;
        String userPath = request.getServletPath();
        // validasi login
        String action = request.getParameter("action");
        if (ubean != null) {
            if (ubean.getRole() == 3 || ubean.getRole() == 4) {
                // action merupakan parameter action saat servlet dipanggil
                if (request.getParameter("action") == null) {
                    // apabila parameter action = null
                    halamanPelaporan(request, response);
                } else if (action.equals("add")) {
                    // apabila action = 'add', ke halaman tambah pelaporan
                    halamanTambahPelaporan(request, response);
                } else if (action.equals("edit")) {
                    // apabila action = 'edit', ke halaman edit pelaporan
                    halamanEditPelaporan(request, response);
                } else if (action.equals("delete")) {
                    // apabila action = 'delete', ke halaman delete
                    deletePelaporan(request, response);
                }
            } else if (ubean.getRole() == 2) {
                if (action.equals("validasi")) {
                    halamanValidasi(request, response);
                } else if (action.equals("valid")) {
                    halamanEditValidasi(request, response);
                }
            } else {
                response.sendError(401);
            }
        } else { // apabila belum login
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/front/login.jsp");
            rd.forward(request, response);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // get session
        session = request.getSession();
        // mengambil object sesiUser dari session
        UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
        String path = request.getServletPath();
        if (sesiUser != null) {
            if (sesiUser.getRole() == 3 || sesiUser.getRole() == 4) {
                if (path.equals("/tambahpelaporan")) {
                    tambahPelaporan(request, response);
                } else if (path.equals("/editpelaporan")) {
                    editPelaporan(request, response);
                }
            } else if (sesiUser.getRole() == 2) {
                if (path.equals("/validasi")) {
                    doValidasi(request, response, 1);
                } else if (path.equals("/tolakvalidasi")) {
                    doValidasi(request, response, -1);
                }
            } else {
                response.sendError(401);
            }
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void halamanTambahPelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // set judul halaman, dan value untuk tombol form 
        request.setAttribute("title", "Tambah Pelaporan");
        request.setAttribute("buttonName", "Tambah");
        // set dataPelaporan kosong (karena halaman tambah pelaporan mendefine datapelaporan)
        request.setAttribute("dataPelaporan", new PelaporanBean());
        request.setAttribute("actAddress", "tambahpelaporan");
        // redirect ke halaman insert_pelaporan
        RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/insert_pelaporan.jsp");
        rd.forward(request, response);
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void halamanEditPelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // set judul halaman, dan value untuk tombol form
        request.setAttribute("title", "Edit Pelaporan");
        request.setAttribute("buttonName", "Edit");
        // mengambil id pelaporan yang akan di edit
        int id = Integer.valueOf(request.getParameter("id"));
        // mendapatkan data pelaporan yang akan diedit berdasarkan id
        listdata = new PelaporanDB().getPelaporanById(id);
        dataPelaporan = (PelaporanBean) listdata.get(0);
        // memasukkan data pelaproan ke dalam atribut
        request.setAttribute("dataPelaporan", dataPelaporan);
        request.setAttribute("actAddress", "editpelaporan");
        // redirect ke halaman insert_pelaporan untuk mengedit halaman
        RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/insert_pelaporan.jsp");
        rd.forward(request, response);
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void tambahPelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        try {
            File file;
            int maxFileSize = 5000 * 1024;
            int maxMemSize = 5000 * 1024;

            String filePath = "D:\\kuliah\\smt5\\RBPL\\#FP\\siperanas\\web\\upload\\file_";

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // ukuran maksimal yang dapat disimpan dalam memori
            factory.setSizeThreshold(maxMemSize);
            // lokasi penyimpanan apabila data lebih besar ukurannya maxMemSize.
            factory.setRepository(new File("c:\\temp"));
            // file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // ukuran maksimum file yang dapat diupload
            upload.setSizeMax(maxFileSize);

            List<FileItem> items = upload.parseRequest(request);
            dataPelaporan = new PelaporanBean();
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String value = item.getString();

                    if (fieldname.equals("nama")) {
                        dataPelaporan.setNamasungai(value);
                        //out.println("nama:" + value);
                    } else if (fieldname.equals("lokasi")) {
                        dataPelaporan.setLokasisungai(value);
                        //out.println("lokasi:" + value);
                    } else if (fieldname.equals("deskripsi")) {
                        dataPelaporan.setDeskripsi(value);
                        //out.println("deskripsi:" + value);
                    } else if (fieldname.equals("warna")) {
                        dataPelaporan.setWarnasungai(Integer.valueOf(value));
                        //out.println("warna:" + value);
                    } else if (fieldname.equals("bau")) {
                        dataPelaporan.setBausungai(Integer.valueOf(value));
                        //out.println("bau:" + value);
                    } else if (fieldname.equals("sampah")) {
                        dataPelaporan.setAdanyasampah(Integer.valueOf(value));
                        //out.println("sampah:" + value);
                    } else if (fieldname.equals("suhu")) {
                        if (value.isEmpty()) {
                            dataPelaporan.setSuhusungai(0);
                        } else {
                            dataPelaporan.setSuhusungai(Double.valueOf(value));
                        }
                        //out.println("suhu:" + value);
                    } else if (fieldname.equals("ph") && !fieldname.isEmpty()) {
                        if (value.isEmpty()) {
                            dataPelaporan.setSuhusungai(0);
                        } else {
                            dataPelaporan.setSuhusungai(Double.valueOf(value));
                        }
                        //out.println("ph:" + value);
                    }
                } else {
                    // Process form file field (input type="file").
                    // Get the uploaded file parameters
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath
                                + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath
                                + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    item.write(file);

                    dataPelaporan.setFotosungai("file_" + fileName);
                    // out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                    // ... (do your job here)
                }
            }

            dataPelaporan.setStatus(0);
            session = request.getSession();
            UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
            dataPelaporan.setIdUser(sesiUser.getIdUser());
            pelaporandb = new PelaporanDB();
            pelaporandb.insertPelaporan(dataPelaporan);
            // redirect ke halaman pelaporan
            halamanPelaporan(request, response);
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     */
    public void editPelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        try {
            File file;
            int maxFileSize = 5000 * 1024;
            int maxMemSize = 5000 * 1024;

            String filePath = "D:\\kuliah\\smt5\\RBPL\\#FP\\siperanas\\web\\upload\\file_";

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // ukuran maksimal yang dapat disimpan dalam memori
            factory.setSizeThreshold(maxMemSize);
            // lokasi penyimpanan apabila data lebih besar ukurannya maxMemSize.
            factory.setRepository(new File("c:\\temp"));
            // file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // ukuran maksimum file yang dapat diupload
            upload.setSizeMax(maxFileSize);

            List<FileItem> items = upload.parseRequest(request);
            dataPelaporan = new PelaporanBean();
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String value = item.getString();

                    if (fieldname.equals("nama")) {
                        dataPelaporan.setNamasungai(value);
                        //out.println("nama:" + value);
                    } else if (fieldname.equals("lokasi")) {
                        dataPelaporan.setLokasisungai(value);
                        //out.println("lokasi:" + value);
                    } else if (fieldname.equals("deskripsi")) {
                        dataPelaporan.setDeskripsi(value);
                        //out.println("deskripsi:" + value);
                    } else if (fieldname.equals("warna")) {
                        dataPelaporan.setWarnasungai(Integer.valueOf(value));
                        //out.println("warna:" + value);
                    } else if (fieldname.equals("bau")) {
                        dataPelaporan.setBausungai(Integer.valueOf(value));
                        //out.println("bau:" + value);
                    } else if (fieldname.equals("sampah")) {
                        dataPelaporan.setAdanyasampah(Integer.valueOf(value));
                        //out.println("sampah:" + value);
                    } else if (fieldname.equals("suhu")) {
                        dataPelaporan.setSuhusungai(Double.valueOf(value));
                        //out.println("suhu:" + value);
                    } else if (fieldname.equals("ph")) {
                        dataPelaporan.setPhsungai(Double.valueOf(value));
                        //out.println("ph:" + value);
                    } else if (fieldname.equals("id")) {
                        dataPelaporan.setIdPelaporan(Integer.valueOf(value));
                    }
                } else {
                    // Process form file field (input type="file").
                    // Get the uploaded file parameters
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath
                                + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath
                                + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    item.write(file);

                    dataPelaporan.setFotosungai("file_" + fileName);
                    // out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                    // ... (do your job here)
                }
            }

            dataPelaporan.setStatus(0);
            pelaporandb = new PelaporanDB();
            pelaporandb.updatePelaporan(dataPelaporan);
            halamanPelaporan(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
//        try {
//            // membuat object dataPelaporan
//            dataPelaporan = new PelaporanBean();
//            // set dataPelaporan yang akan di edit
//            dataPelaporan.setIdPelaporan(Integer.valueOf(request.getParameter("id")));
//            dataPelaporan.setNamasungai(request.getParameter("nama"));
//            dataPelaporan.setLokasisungai(request.getParameter("lokasi"));
//            dataPelaporan.setDeskripsi(request.getParameter("deskripsi"));
//            dataPelaporan.setWarnasungai(Integer.valueOf(request.getParameter("warna")));
//            dataPelaporan.setBausungai(Integer.valueOf(request.getParameter("bau")));
//            dataPelaporan.setAdanyasampah(Integer.valueOf(request.getParameter("sampah")));
//            dataPelaporan.setSuhusungai(Double.valueOf(request.getParameter("suhu")));
//            dataPelaporan.setPhsungai(Double.valueOf(request.getParameter("ph")));
//            dataPelaporan.setStatus(0);
//            // memasukkannya dalam database
//            pelaporandb = new PelaporanDB();
//            pelaporandb.updatePelaporan(dataPelaporan);
//            // redirect ke halaman pelaporan
//            halamanPelaporan(request, response);
//        } catch (ClassNotFoundException ex) {
//            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (SQLException ex) {
//            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws undException
     */
    public void deletePelaporan(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // mengambil id pelaporan yang akan didelete
            int id = Integer.valueOf(request.getParameter("id"));
            // melakukan aksi delete pelaproan dari database
            pelaporandb = new PelaporanDB();
            pelaporandb.deletePelaporan(id);
            // redirect ke halaman pelaporan
            halamanPelaporan(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     *
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.lang.ClassNotFoundException
     */
    public void halamanValidasi(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            session = request.getSession();
            UserBean sesiUser = (UserBean) session.getAttribute("sesiUser");
            listdata = new PelaporanDB().getAllPelaporan();
            request.setAttribute("listdata", listdata);
            request.setAttribute("title", "Validasi");
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/validasi.jsp");
            rd.forward(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void halamanEditValidasi(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("title", "Validasi Pelaporan");
        request.setAttribute("buttonName", "Edit");
        int id = Integer.valueOf(request.getParameter("id"));
        listdata = new PelaporanDB().getPelaporanById(id);
        if (listdata.size() != 0) {
            dataPelaporan = (PelaporanBean) listdata.get(0);
            request.setAttribute("dataPelaporan", dataPelaporan);
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/view/insert_pelaporan.jsp");
            rd.forward(request, response);
        } else {
            //response.sendError(404,"Data tidak ada");
            //setAttribute("message", "Data pelaporan tidak tersedia!");
            response.sendRedirect("pelaporan?action=validasi");
        }
    }

    /**
     *
     * @param request
     * @param response
     * @param status
     * @throws ServletException
     * @throws IOException
     */
    public void doValidasi(HttpServletRequest request, HttpServletResponse response, int status)
            throws ServletException, IOException {
        try {
            int id = Integer.valueOf(request.getParameter("id"));
            listdata = new PelaporanDB().getPelaporanById(id);
            dataPelaporan = (PelaporanBean) listdata.get(0);
            dataPelaporan.setStatus(status);
            pelaporandb = new PelaporanDB();
            pelaporandb.updatePelaporan(dataPelaporan);
            halamanValidasi(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(PelaporanServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
